{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import cv2 as cv\n",
    "import os\n",
    "\n",
    "from glob import glob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "camera_id = 0\n",
    "out_folder = '/tmp/imgs/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from reachy.utils.vision import BackgroundVideoCapture\n",
    "\n",
    "cap = BackgroundVideoCapture(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "_, img = cap.read()\n",
    "plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\n",
    "\n",
    "from IPython.display import display, clear_output\n",
    "\n",
    "button = widgets.Button(description=\"Snapshot!\")\n",
    "output = widgets.Output()\n",
    "\n",
    "display(button, output)\n",
    "\n",
    "\n",
    "def on_button_clicked(b):\n",
    "    n = len(glob(os.path.join(out_folder, '*.jpg'))) + 1\n",
    "    path = os.path.join(out_folder, f'img_{n}.jpg')\n",
    "    \n",
    "    _, img = cap.read()\n",
    "    cv.imwrite(path, img)\n",
    "\n",
    "    with output:\n",
    "        clear_output()\n",
    "        print(f'Snapshot saved as {path}')\n",
    "\n",
    "\n",
    "button.on_click(on_button_clicked)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
